package org.phantom.securityframework.datapermission.internal;

import java.lang.annotation.Annotation;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.phantom.securityframework.api.datapermission.DimensionType;
import org.phantom.securityframework.datapermission.DataFilter;
import org.phantom.securityframework.datapermission.DimensionQuery;
import org.phantom.securityframework.datapermission.SqlBuilder;
import org.springframework.stereotype.Service;

/**
 * sql生成器默认实现.只拼装简单sql
 * @author apple
 *
 */
@Service("sqlBuildDefaultImpl")
public class SqlBuildDefaultImpl implements SqlBuilder{

	@Override
	public String build(Annotation anno, DimensionQuery dimensionQuery) {
		DataFilter dataFilter = (DataFilter) anno;
		DimensionQueryDefaultImpl query = (DimensionQueryDefaultImpl) dimensionQuery;
		StringBuilder sb = new StringBuilder("select * from (select * from ").append(dataFilter.table());
		if(query==null || query.getDimensionMappedValue()==null){
			sb.append(")");
			return sb.toString();
		}
		sb.append(this.buildCondition(anno, query));
		sb.append(")");
		return sb.toString();
	}
	@Override
	public String buildCount(Annotation anno, DimensionQuery dimensionQuery) {
		DataFilter dataFilter = (DataFilter) anno;
		DimensionQueryDefaultImpl query = (DimensionQueryDefaultImpl) dimensionQuery;
		StringBuilder sb = new StringBuilder("select count(*) from (select * from ").append(dataFilter.table());
		if(query==null || query.getDimensionMappedValue()==null){
			sb.append(")");
			return sb.toString();
		}
		sb.append(this.buildCondition(anno, query));
		sb.append(")");
		return sb.toString();
	}
	protected String buildCondition(Annotation anno,DimensionQuery dimensionQuery){
		DataFilter dataFilter = (DataFilter) anno;
		DimensionQueryDefaultImpl query = (DimensionQueryDefaultImpl) dimensionQuery;
		StringBuilder sb = new StringBuilder();
		Iterator<Entry<String, List<DimensionType>>> it = query.getDimensionMappedValue().entrySet().iterator();
		if(it.hasNext())
			sb.append(" where ");
		for(int n=0;n<query.getDimensionMappedValue().size();n++){
			Entry<String, List<DimensionType>> entry = it.next();
			List<DimensionType> l = entry.getValue();
			sb.append(entry.getKey());
			if(l.size()==1){
				if(l.get(0).getSymbol().equalsIgnoreCase("like"))
					sb.append(" like '%").append(l.get(0).getValue()).append("'");
				else
					sb.append("=").append(l.get(0).getValue());
			}else{
				sb.append(" in(");
				for (int i=0;i<l.size();i++) {
					DimensionType o = l.get(i);
					sb.append(o.getValue());
					if(i<l.size()-1)
						sb.append(",");
				}
				sb.append(")");
			}
			if(n<query.getDimensionMappedValue().size()-1)
				sb.append(" ").append(dataFilter.separator()).append(" ");
		}
		return sb.toString();
				
	}

}
